package clock.socoolby.com.clock.fragment.digit;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.jaygoo.widget.VerticalRangeSeekBar;
import com.openbravo.data.basic.BasicException;

import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.R;
import clock.socoolby.com.clock.ThemeUIManager;
import clock.socoolby.com.clock.fragment.simulate.SimulateClockFragment;
import clock.socoolby.com.clock.pop.ColorPickerPop;
import clock.socoolby.com.clock.state.ClockInterfaceTypeEnum;
import clock.socoolby.com.clock.utils.DialogUtils;
import clock.socoolby.com.clock.viewmodel.DigitViewModel;
import clock.socoolby.com.clock.viewmodel.GlobalViewModel;
import clock.socoolby.com.clock.viewmodel.ThemeUIViewModel;
import clock.socoolby.com.clock.viewmodel.ViewModelFactory;
import clock.socoolby.com.clock.widget.textview.ShadowTypeEnum;
import clock.socoolby.com.clock.widget.textview.charanimator.CharAnimatorEnum;

public class DigitClockConfigFragment extends Fragment {

    public static final String TAG = SimulateClockFragment.class.getSimpleName();

    public static final String NAME = "simulateClockConfig";

    DigitViewModel digitViewModel;
    GlobalViewModel globalViewModel;
    ThemeUIViewModel themeUIViewModel;
    ThemeUIManager themeUIManager;

    @BindView(R.id.tv_hourSystem12)
    RadioButton tvHourSystem12;
    @BindView(R.id.tv_hourSystem24)
    RadioButton tvHourSystem24;
    @BindView(R.id.tv_hourSystem_group)
    RadioGroup tvHourSystemGroup;
    @BindView(R.id.tv_secoundShow)
    CheckBox tvSecoundShow;
    @BindView(R.id.text_style_group1)
    LinearLayout textStyleGroup1;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.tv_textStyle_numal)
    RadioButton tvTextStyleNumal;
    @BindView(R.id.tv_textStyle_shadow)
    RadioButton tvTextStyleShadow;
    @BindView(R.id.tv_textStyle_relief)
    RadioButton tvTextStyleRelief;
    @BindView(R.id.tv_textStyle_group)
    RadioGroup tvTextStyleGroup;
    @BindView(R.id.tv_textStyle_reflect)
    CheckBox tvTextStyleReflect;
    @BindView(R.id.text_style_group2)
    LinearLayout textStyleGroup2;
    @BindView(R.id.tv_textAnim_down)
    RadioButton tvTextAnimDown;
    @BindView(R.id.tv_textAnim_up)
    RadioButton tvTextAnimUp;
    @BindView(R.id.tv_textAnim_downflit)
    RadioButton tvTextAnimDownflit;
    @BindView(R.id.tv_textAnim_upflat)
    RadioButton tvTextAnimUpflat;
    @BindView(R.id.tv_textAnim_group)
    RadioGroup tvTextAnimGroup;
    @BindView(R.id.text_style_group3)
    LinearLayout textStyleGroup3;
    @BindView(R.id.tv_textAnim_numal)
    RadioButton tvTextAnimNumal;
    @BindView(R.id.textView2)
    CheckBox textView2;
    @BindView(R.id.button4)
    Button button4;
    @BindView(R.id.button5)
    Button button5;
    @BindView(R.id.button6)
    Button button6;
    @BindView(R.id.button7)
    Button button7;
    @BindView(R.id.button8)
    Button button8;
    @BindView(R.id.text_style_group4)
    LinearLayout textStyleGroup4;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.editText)
    TextView textView1;
    @BindView(R.id.tv_themeUI_style_1)
    Button tvThemeUIStyle1;
    @BindView(R.id.tv_themeUI_style_2)
    Button tvThemeUIStyle2;
    @BindView(R.id.tv_themeUI_style_3)
    Button tvThemeUIStyle3;
    @BindView(R.id.tv_themeUI_style_4)
    Button tvThemeUIStyle4;
    @BindView(R.id.tv_textAnim_tabDigit_up)
    RadioButton tvTextAnimTabDigitUp;
    @BindView(R.id.tv_theme_config_recover)
    Button tvThemeConfigRecover;
    @BindView(R.id.button_round)
    Button buttonRound;
    @BindView(R.id.tv_SecondSubscript)
    CheckBox tvSecondSubscript;
    @BindView(R.id.tv_textStyle_border)
    CheckBox tvTextStyleBorder;
    @BindView(R.id.tv_textStyle_border_color)
    Button tvTextStyleBorderColor;
    @BindView(R.id.tv_time_text_basline_down)
    VerticalRangeSeekBar tvTimeTextBaslineDown;
    @BindView(R.id.tv_textStyle_border_divider_color)
    Button tvTextStyleBorderDividerColor;
    @BindView(R.id.tv_time_text_subscript_scale)
    VerticalRangeSeekBar tvTimeTextSubscriptScale;
    @BindView(R.id.tv_time_text_padding)
    VerticalRangeSeekBar tvTimeTextPadding;
    @BindView(R.id.tv_textStyle_border_doubble)
    CheckBox tvTextStyleBorderDoubble;
    @BindView(R.id.tv_time_text_basline_x)
    VerticalRangeSeekBar tvTimeTextBaslineX;

    public DigitClockConfigFragment(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        globalViewModel = ViewModelProviders.of(getActivity(), new ViewModelFactory(ClockApplication.getInstance().getModel())).get(GlobalViewModel.class);
        digitViewModel = ViewModelProviders.of(getActivity(), new ViewModelFactory(ClockApplication.getInstance().getModel())).get(DigitViewModel.class);
        themeUIViewModel=ViewModelProviders.of(getActivity(), new ViewModelFactory(ClockApplication.getInstance().getModel())).get(ThemeUIViewModel.class);
        themeUIManager=globalViewModel.getThemeUIManager();
        themeUIManager.saveTempThemeUI(ClockInterfaceTypeEnum.Digit.code);
        globalViewModel.setAppConfig(true);
    }

    private Unbinder unbinder;

    private ColorPickerPop colorPickerDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_digit_config, container, false);

        unbinder = ButterKnife.bind(this, view);

        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //getFragmentManager().popBackStack();
                themeUIViewModel.loadFromModel();
                return true;
            }
        });

        tvTimeTextBaslineDown.setTickMarkTextArray(new CharSequence[]{"下", "位移", "上"});

        tvTimeTextBaslineX.setTickMarkTextArray(new CharSequence[]{"右", "位移", "左"});

        tvTimeTextSubscriptScale.setTickMarkTextArray(new CharSequence[]{"1", "秒比", "100"});

        tvTimeTextPadding.setTickMarkTextArray(new CharSequence[]{"0", "间隔", "20"});


        loadForViewModel();

        tvHourSystemGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.tv_hourSystem12:
                    case R.id.tv_hourSystem24:
                        globalViewModel.setHourSystem12(tvHourSystem12.isChecked());
                        break;
                    default:
                        break;
                }
            }
        });


        tvTextStyleGroup.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
            ShadowTypeEnum shadowTypeEnum = ShadowTypeEnum.NOSETUP;
            switch (checkedId) {
                case R.id.tv_textStyle_numal:
                    shadowTypeEnum = ShadowTypeEnum.NOSETUP;
                    break;
                case R.id.tv_textStyle_shadow:
                    shadowTypeEnum = ShadowTypeEnum.SHADOW;
                    break;
                case R.id.tv_textStyle_relief:
                    shadowTypeEnum = ShadowTypeEnum.RELIEF;
                    break;
            }
            digitViewModel.setShadowType(shadowTypeEnum);
        });

        tvSecoundShow.setOnCheckedChangeListener((group, checkedId) ->
        {
            digitViewModel.setDisplaySecond(group.isChecked());
        });

        tvTextStyleReflect.setOnCheckedChangeListener((group, checkedId) -> {
            digitViewModel.setReflectedAble(group.isChecked());
        });

        tvTextAnimGroup.setOnCheckedChangeListener((group, checkedId) -> {
            CharAnimatorEnum charAnimatorEnum = CharAnimatorEnum.NOSETUP;
            switch (checkedId) {
                case R.id.tv_textAnim_down:
                    charAnimatorEnum = CharAnimatorEnum.UP2DOWN;
                    break;
                case R.id.tv_textAnim_up:
                    charAnimatorEnum = CharAnimatorEnum.DOWN2UP;
                    break;
                case R.id.tv_textAnim_downflit:
                    charAnimatorEnum = CharAnimatorEnum.Marquee3D_Down;
                    break;
                case R.id.tv_textAnim_upflat:
                    charAnimatorEnum = CharAnimatorEnum.Marquee3D_Up;
                    break;
                case R.id.tv_textAnim_tabDigit_up:
                    charAnimatorEnum = CharAnimatorEnum.TabDigit;
                    break;
            }
            if (charAnimatorEnum != CharAnimatorEnum.NOSETUP)
                if (digitViewModel.getDisplaySecond().getValue())
                    digitViewModel.setTimeText("88:88:88");
                else
                    digitViewModel.setTimeText("88:88");
            digitViewModel.setTimeCharAnimatorType(charAnimatorEnum);
        });

        textView2.setOnCheckedChangeListener((group, checkedId) -> {
            digitViewModel.setLinearGradientAble(textView2.isChecked());
        });

        button4.setOnClickListener(view1 ->
                changeGradientColor(button4, 0)
        );

        button5.setOnClickListener((view1) -> {
            changeGradientColor(button5, 1);
        });

        button6.setOnClickListener(view1 -> {
            changeGradientColor(button6, 2);
        });

        button7.setOnClickListener((view1) -> {
            changeGradientColor(button7, 3);
        });

        button8.setOnClickListener((view1) -> {
            changeGradientColor(button8, 4);
        });

        buttonRound.setOnClickListener(view1 -> {
            for (int i = 0; i < confColors.length; i++)
                confColors[i] = roundColor();
            digitViewModel.setTimeLinearGradientColorsArray(confColors);
            button4.setBackgroundColor(confColors[0]);
            button5.setBackgroundColor(confColors[1]);
            button6.setBackgroundColor(confColors[2]);
            button7.setBackgroundColor(confColors[3]);
            button8.setBackgroundColor(confColors[4]);
        });

        tvThemeUIStyle1.setOnClickListener(v -> changeThemeUIStyle(1));

        tvThemeUIStyle2.setOnClickListener(v -> changeThemeUIStyle(2));

        tvThemeUIStyle3.setOnClickListener(v -> changeThemeUIStyle(3));

        tvThemeUIStyle4.setOnClickListener(v -> changeThemeUIStyle(4));

        tvThemeUIStyle1.setOnLongClickListener(v -> configThemeUIStyle(1));

        tvThemeUIStyle2.setOnLongClickListener(v -> configThemeUIStyle(2));

        tvThemeUIStyle3.setOnLongClickListener(v -> configThemeUIStyle(3));

        tvThemeUIStyle4.setOnLongClickListener(v -> configThemeUIStyle(4));

        tvThemeConfigRecover.setOnClickListener(v -> {
            try {
                themeUIManager.recoverTempThemeUI(ClockInterfaceTypeEnum.Digit.code);
                reloadViewModel();
            } catch (BasicException e) {
                e.printStackTrace();
            }
        });

        tvSecondSubscript.setOnCheckedChangeListener((group, checkedId) -> {
            digitViewModel.setSecondSubscript(tvSecondSubscript.isChecked());
            tvTimeTextSubscriptScale.setVisibility(tvSecondSubscript.isChecked() ? View.VISIBLE : View.GONE);
        });

        tvTextStyleBorder.setOnCheckedChangeListener((group, checkedId) -> {
            digitViewModel.setCharBackgroundBorder(tvTextStyleBorder.isChecked());
        });

        tvTextStyleBorderColor.setOnClickListener(v -> {
            if (colorPickerDialog == null)
                colorPickerDialog = new ColorPickerPop(getActivity());

            colorPickerDialog.setOnColorChangeListenter(new ColorPickerPop.OnColorListener() {
                @Override
                public void onEnsure(int color) {
                    digitViewModel.setCharBackgroundBorderColor(color);
                    tvTextStyleBorderColor.setBackgroundColor(color);
                }

                @Override
                public void onBack() {
                }
            });
            colorPickerDialog.show(digitViewModel.getCharBackgroundBorderColor().getValue());
        });

        tvTextStyleBorderDividerColor.setOnClickListener(v -> {
            if (colorPickerDialog == null)
                colorPickerDialog = new ColorPickerPop(getActivity());

            colorPickerDialog.setOnColorChangeListenter(new ColorPickerPop.OnColorListener() {
                @Override
                public void onEnsure(int color) {
                    digitViewModel.setCharBackgroundBorderDividerColor(color);
                    tvTextStyleBorderDividerColor.setBackgroundColor(color);
                }

                @Override
                public void onBack() {
                }
            });
            colorPickerDialog.show(digitViewModel.getCharBackgroundBorderColor().getValue());
        });

        tvTextStyleBorderDoubble.setOnCheckedChangeListener((group, checkedId) -> {
            digitViewModel.setCharBackgroundBorderWithDoubble(tvTextStyleBorderDoubble.isChecked());
        });

        tvTimeTextBaslineDown.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                digitViewModel.setBaseLineDown(new Float(leftValue - 100).intValue());
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });

        tvTimeTextBaslineX.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                digitViewModel.setBaseLineX(new Float(leftValue - 100).intValue());
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });

        tvTimeTextSubscriptScale.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                digitViewModel.setSubscriptFontScale(new Float(leftValue).intValue());
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });

        tvTimeTextPadding.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                digitViewModel.setTimeTextPadding(new Float(leftValue).intValue());
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });

        return view;
    }

    private void changeThemeUIStyle(int order) {
        String styleName = "digit_style_" + order;
        try {
            if (themeUIManager.exitsThemeUIStyle(ClockInterfaceTypeEnum.Digit.code, styleName)) {
                themeUIManager.loadDigitThemeFromDB(styleName);
                reloadViewModel();
            } else {
                DialogUtils.show(getActivity(), "温馨提示", "当前主题还未设置,是否以当前主题保存.", ok -> {
                    if (ok)
                        configThemeUIStyle(order);
                });
                Toast.makeText(getActivity(), "你可长按来保存一个主题", Toast.LENGTH_SHORT).show();
            }
        } catch (BasicException e) {
            e.printStackTrace();
        }
    }

    private boolean configThemeUIStyle(int order) {
        String styleName = "digit_style_" + order;
        try {
            themeUIManager.saveDigitThemeFromModel(styleName);
            Toast.makeText(getActivity(), "当前主题已保存", Toast.LENGTH_SHORT).show();
        } catch (BasicException e) {
            e.printStackTrace();
        }
        return true;
    }

    private void changeGradientColor(Button view, int order) {
        if (colorPickerDialog == null)
            colorPickerDialog = new ColorPickerPop(getActivity());

        colorPickerDialog.setOnColorChangeListenter(new ColorPickerPop.OnColorListener() {
            @Override
            public void onEnsure(int color) {
                confColors[order] = color;
                digitViewModel.setTimeLinearGradientColorsArray(confColors);
                view.setBackgroundColor(color);
            }

            @Override
            public void onBack() {
            }
        });
        colorPickerDialog.show(confColors[order]);
    }

    private void reloadViewModel() {
        globalViewModel.loadFromModel();
        digitViewModel.loadFromModel();
        loadForViewModel();
    }

    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        globalViewModel.setAppConfig(false);
        unbinder.unbind();
    }

    Integer[] defGradientColorsArray = new Integer[]{Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK, Color.BLACK};
    Integer[] confColors;

    private void loadForViewModel() {

        if (globalViewModel.getHourSystem12().getValue())
            tvHourSystem12.setChecked(true);
        else
            tvHourSystem24.setChecked(true);


        tvSecoundShow.setChecked(digitViewModel.getDisplaySecond().getValue());


        switch (digitViewModel.getShadowType().getValue()) {
            case NOSETUP:
                tvTextStyleNumal.setChecked(true);
                break;
            case RELIEF:
                tvTextStyleRelief.setChecked(true);
                break;
            case SHADOW:
                tvTextStyleShadow.setChecked(true);
                break;
        }


        tvTextStyleReflect.setChecked(digitViewModel.getReflectedAble().getValue());

        switch (digitViewModel.getTimeCharAnimatorType().getValue()) {
            case NOSETUP:
                tvTextAnimNumal.setChecked(true);
                break;
            case UP2DOWN:
                tvTextAnimDown.setChecked(true);
                break;
            case DOWN2UP:
                tvTextAnimUp.setChecked(true);
                break;
            case Marquee3D_Down:
                tvTextAnimDownflit.setChecked(true);
                break;
            case Marquee3D_Up:
                tvTextAnimUpflat.setChecked(true);
                break;
            case TabDigit:
                tvTextAnimTabDigitUp.setChecked(true);
                break;
        }

        textView2.setChecked(digitViewModel.getLinearGradientAble().getValue());

        confColors = digitViewModel.getTimeLinearGradientColorsArray().getValue();

        if (confColors == null)
            confColors = defGradientColorsArray;

        button4.setBackgroundColor(confColors[0]);
        button5.setBackgroundColor(confColors[1]);
        button6.setBackgroundColor(confColors[2]);
        button7.setBackgroundColor(confColors[3]);
        button8.setBackgroundColor(confColors[4]);


        digitViewModel.getLinearGradientAble().observe(this, (able) -> {
            button4.setClickable(able);
            button5.setClickable(able);
            button6.setClickable(able);
            button7.setClickable(able);
            button8.setClickable(able);
            buttonRound.setClickable(able);
        });

        setTextColor(globalViewModel.getForegroundColor().getValue());

        tvSecondSubscript.setChecked(digitViewModel.getSecondSubscript().getValue());

        tvTextStyleBorder.setChecked(digitViewModel.getCharBackgroundBorder().getValue());
        tvTextStyleBorderColor.setBackgroundColor(digitViewModel.getCharBackgroundBorderColor().getValue());
        tvTextStyleBorderDividerColor.setBackgroundColor(digitViewModel.getCharBackgroundBorderDividerColor().getValue());

        tvTextStyleBorderDoubble.setChecked(digitViewModel.getCharBackgroundBorderWithDoubble().getValue());

        float baseLineDown = 100f + digitViewModel.getBaseLineDown().getValue();
        if (baseLineDown > 200)
            baseLineDown = 200;
        else if (baseLineDown < 0)
            baseLineDown = 100;
        tvTimeTextBaslineDown.setProgress(baseLineDown);

        baseLineDown = 100f + digitViewModel.getBaseLineX().getValue();
        if (baseLineDown > 200)
            baseLineDown = 200;
        else if (baseLineDown < 0)
            baseLineDown = 100;
        tvTimeTextBaslineX.setProgress(baseLineDown);

        tvTimeTextSubscriptScale.setVisibility(digitViewModel.getDisplaySecond().getValue() ? View.VISIBLE : View.GONE);
        tvTimeTextSubscriptScale.setProgress(digitViewModel.getSubscriptFontScale().getValue());

        digitViewModel.getCharBackgroundBorder().observe(this, (able) -> {
            tvTextStyleBorderColor.setClickable(able);
            tvTextStyleBorderDividerColor.setClickable(able);
            tvTextStyleBorderDoubble.setClickable(able);
        });

        tvTimeTextPadding.setProgress(digitViewModel.getTimeTextPadding().getValue());

    }

    private void setTextColor(int color) {

        tvHourSystem12.setTextColor(color);
        tvHourSystem24.setTextColor(color);

        tvSecoundShow.setTextColor(color);
        tvSecondSubscript.setTextColor(color);

        textView3.setTextColor(color);

        tvTextStyleNumal.setTextColor(color);
        tvTextStyleShadow.setTextColor(color);
        tvTextStyleRelief.setTextColor(color);
        tvTextStyleReflect.setTextColor(color);

        tvTextAnimDown.setTextColor(color);
        tvTextAnimUp.setTextColor(color);
        tvTextAnimDownflit.setTextColor(color);
        tvTextAnimUpflat.setTextColor(color);
        tvTextAnimNumal.setTextColor(color);
        tvTextAnimTabDigitUp.setTextColor(color);

        textView2.setTextColor(color);
        textView1.setTextColor(color);
        textView.setTextColor(color);

        button4.setTextColor(color);
        button5.setTextColor(color);
        button6.setTextColor(color);
        button7.setTextColor(color);
        button8.setTextColor(color);
        buttonRound.setTextColor(color);

        tvThemeUIStyle1.setTextColor(color);
        tvThemeUIStyle2.setTextColor(color);
        tvThemeUIStyle3.setTextColor(color);
        tvThemeUIStyle4.setTextColor(color);

        tvTextStyleBorder.setTextColor(color);
        tvTextStyleBorderColor.setTextColor(color);
        tvTextStyleBorderDividerColor.setTextColor(color);
        tvTextStyleBorderDoubble.setTextColor(color);

        tvTimeTextBaslineDown.setTickMarkTextColor(color);
        tvTimeTextSubscriptScale.setTickMarkTextColor(color);
        tvTimeTextPadding.setTickMarkTextColor(color);
    }

    static Random rand = new Random();

    public static int roundColor() {
        int alpha = 200;
        int r = rand.nextInt(255);
        int g = rand.nextInt(255);
        int b = rand.nextInt(255);
        return alpha << 24 | r << 16 | g << 8 | b;
    }
}
